<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @keyup.enter.native="search()"
    >
      <el-form-item label="名片名称">
        <br />
        <br />
        <el-input
          style="margin-left:-70px;width:200px"
          v-model="formInline.cardName"
          placeholder
          clearable
        ></el-input>
      </el-form-item>

      <el-form-item label="名片类型">
        <br />
        <br />
        <el-select
          style="margin-left:-70px;width:200px"
          v-model="formInline.cardType"
        >
          <el-option label="全部" value></el-option>
          <el-option label="商品分享名片" value="1"></el-option>
          <el-option label="活动分享名片" value="2"></el-option>
          <el-option label="店铺分享名片" value="3"></el-option>
        </el-select>
      </el-form-item>
      <div style="width:100%;display:flex;justify-content:flex-end;">
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="search()"
            size="mini"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="kong()"
            size="mini"
            icon="el-icon-delete"
            >清空</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="toAdd()"
            icon="el-icon-edit"
            size="mini"
            >新增</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-table
      :data="tableData"
      v-loading="loading"
      border
      height="400px"
      style="width: 100%;"
      :header-cell-style="{ background: '#ebecf0', color: '#606266' }"
    >
      <el-table-column
        type="index"
        width="60"
        label="序号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="cardType"
        label="名片类型"
        header-align="center"
        width="160"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.cardType == '1'">商品分享名片</span>
          <span v-if="scope.row.cardType == '2'">活动分享名片</span>
          <span v-if="scope.row.cardType == '3'">店铺分享名片</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="cardName"
        label="名片名称"
        header-align="center"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="fontColor"
        label="匹配字体颜色"
        header-align="center"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.fontColor }}</span>
          <el-color-picker
            v-model="scope.row.fontColor"
            size="mini"
            disabled
          ></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column
        prop="background"
        label="匹配背景底色"
        header-align="center"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.background }}</span>
          <el-color-picker
            v-model="scope.row.background"
            size="mini"
            disabled
          ></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column
        prop="cardPic"
        label="名片背景图片"
        header-align="center"
        width="180"
      >
        <template slot-scope="scope">
          <img
            :src="scope.row.cardPic"
            v-if="scope.row.cardPic != '' && scope.row.cardPic != null"
            width="70"
            height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="isSpecial"
        label="类型"
        header-align="center"
        align="center"
        width="180"
      >
        <template slot-scope="scope">{{
          scope.row.isSpecial == 1 ? '25周年风格名片' : '普通名片'
        }}</template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        header-align="center"
        width="180"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="开展状态" header-align="center" align="center">
        <template slot-scope="scope">
          <span
            v-if="
              scope.row.expiredStatus != '0' &&
                scope.row.expiredStatus != '1' &&
                scope.row.expiredStatus != '2'
            "
            >——</span
          >
          <span v-if="scope.row.expiredStatus == '1'">进行中</span>
          <span v-if="scope.row.expiredStatus == '0'">已结束</span>
          <span v-if="scope.row.expiredStatus == '2'">未开始</span>
        </template>
      </el-table-column>
      <el-table-column
        label="有效期"
        align="center"
        width="250"
        :formatter="dateRange"
      ></el-table-column>

      <el-table-column label="发布状态" align="center" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.publishStatus == '0'">未发布</span>
          <span v-if="scope.row.publishStatus == '1'">已发布</span>
          <span v-if="scope.row.publishStatus == '3'">已删除</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="380"
        align="center"
        header-align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="updatePlanStatus(scope.row.uuid, '1')"
            v-if="scope.row.publishStatus == '0'"
            >发布</el-button
          >
          <el-button
            type="text"
            @click="updatePlanStatus(scope.row.uuid, '0')"
            v-if="scope.row.publishStatus == '1'"
            >撤回</el-button
          >
          <el-button
            type="text"
            @click="toEdit(scope.row)"
            v-show="scope.row.publishStatus != '1'"
            >编辑</el-button
          >
          <el-button type="text" @click="toEdit2(scope.row)"
            >查看详情</el-button
          >
          <!-- <el-button
                        type="text"
                        @click="updatePlanStatus(scope.row.uuid, '3')"
                        v-if="scope.row.status == '0'"
                    >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top:5px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
        :current-page="listQuery.current"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  queryStoreCardInfo,
  updateGoodsActivityStatus,
  //   updatePlanStatus,
  //   deletePromotion
} from '@/api/userCard';
import {
  queryChooseGoodsList,
  saveGoodsActivityWithGoods,
  queryGoodsStoreList,
} from '@/api/userCardEdit';
import XLSX from 'xlsx';
export default {
  data() {
    return {
      logininfo: {},
      orgList: [],
      orgSeq: '',
      loading: true,
      exportLoading: false,
      couponListshop: [],
      tableDataExcel: [],
      listQuery2: {
        current: 1,
        size: 100,
      },
      dialogVisibledetail: false,
      uuid: '',
      formCoupon: {
        shopName: '',
        warzoneName: '',
      },
      formInline: {
        cardName: '',
        cardType: '',
        status: '',
      },
      total: 0,
      total2: 0,
      userId: '',
      listQuery: {
        current: 1,
        size: 100,
      },
      tableData: [],
      currentTime: '',
    };
  },
  mounted() {
    this.promotionList();
  },
  methods: {
    kong() {
      this.formInline.cardName = '';
      this.formInline.status = '';
      this.formInline.cardType = '';
    },
    exportToo() {
      this.exportLoading = true;
      this.getDataListExcel();
    },
    getDataListExcel() {
      let data = {
        size: this.total2,
        current: 1,
        condition: {
          uuid: this.uuid,
          shopName: this.formCoupon.shopName,
          warzoneName: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsStoreList(data).then((res) => {
        if (res.code == 1) {
          this.tableDataExcel = res.records;
          if (this.tableDataExcel.length > 0) {
            this.exportExcel();
          } else {
            this.$message.error('数据为空无法导出!');
          }
        }
        setTimeout(() => {
          this.exportLoading = false;
        }, 3000);
      });
    },
    //全数据页面导出
    exportExcel() {
      this.exportLoading = true;
      //要导出去的标题
      var that = this;
      var arry = [
        ['店铺编码', '专卖店名称', '所属大区', '状态', '参与时间', '结束时间'],
      ];
      that.tableDataExcel
        .map((a, i) => {
          var _arry = [];
          _arry.push(a.authCode);
          _arry.push(a.orgName);
          _arry.push(a.warzoneName);
          _arry.push(a.status == 1 ? '启用' : '未启用');
          _arry.push(a.beginTime == null ? '' : a.beginTime.toString());
          _arry.push(
            a.endTime == null ? '' : a.endTime.toString().substr(0, 10)
          );
          return _arry;
        })
        .forEach((a) => {
          arry.push(a);
        });
      var sheet = XLSX.utils.aoa_to_sheet(arry);
      sheet['!cols'] = [
        {
          wpx: 160, //A
        },
        {
          wpx: 180, //B
        },
        {
          wpx: 180, //C
        },
        {
          wpx: 180, //D
        },
        {
          wpx: 180, //E
        },
        {
          wpx: 180, //E
        },
      ]; //单元格列宽
      this.exportLoading = false;
      this.openDownloadDialog(
        this.sheet2blob(sheet),
        new Date().toLocaleDateString() + '店铺参与详情记录表.xlsx'
      );
    },
    //转下载文件
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1';
      var workbook = {
        SheetNames: [sheetName],
        Sheets: {},
      };
      workbook.Sheets[sheetName] = sheet;
      // 生成excel的配置项
      var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary',
      };
      var wbout = XLSX.write(workbook, wopts);
      var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      // 字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
      return blob;
    },
    //下载文件触发弹窗
    openDownloadDialog(url, saveName) {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
      }
      var aLink = document.createElement('a');
      aLink.href = url;
      aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event;
      if (window.MouseEvent) {
        event = new MouseEvent('click');
      } else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
      }
      aLink.dispatchEvent(event);
    },
    queryChooseGoodsList() {
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: {
          uuid: this.uuid,
          shopName: this.formCoupon.shopName,
          warzoneName: this.formCoupon.warzoneName,
        },
        ascs: [],
        descs: [],
      };
      queryGoodsStoreList(data).then((res) => {
        this.couponListshop = res.records;
        this.total2 = res.total;
      });
    },
    fixData(row, column, cellValue, index) {
      if (cellValue == null || cellValue == '') return '';
      return cellValue.substring(0, 10);
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.promotionList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.promotionList();
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.queryChooseGoodsList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.queryChooseGoodsList();
    },
    indexMethod(index) {
      let curpage = this.listQuery.current; //单前页码，具体看组件取值
      let limitpage = this.listQuery.size; //每页条数，具体是组件取值
      return index + 1 + (curpage - 1) * limitpage;
    },
    search() {
      this.listQuery.current = 1;
      this.promotionList();
    },
    promotionList() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          cardName: this.formInline.cardName,
          cardType: this.formInline.cardType,
          status: this.formInline.status,
        },
        ascs: [],
        descs: [],
      };
      queryStoreCardInfo(data).then((res) => {
        this.loading = false;
        console.log(res.records);
        this.tableData = res.records;
        this.total = res.total;
        this.currentTime = this.format(new Date(), 'yyyy-MM-dd HH:mm:ss');
      });
    },
    format(date, fmt) {
      let o = {
        'M+': date.getMonth() + 1, //月份
        'd+': date.getDate(), //日
        'H+': date.getHours(), //小时
        'm+': date.getMinutes(), //分
        's+': date.getSeconds(), //秒
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        );
      for (let k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          );
      return fmt;
    },
    toAdd() {
      this.$router.push({
        name: 'userCardEdit',
        params: {},
      });
    },
    toEdit(item) {
      this.$router.push({
        name: 'userCardEdit',
        params: {
          edit: item,
          falg: false,
          updateFlag: true,
        },
      });
    },
    toEdit2(item) {
      this.$router.push({
        name: 'userCardEdit',
        params: {
          edit: item,
          falg: true,
        },
      });
    },
    updatePlanStatus(planId, status) {
      var msg = '';
      let publishStatus = status;
      let statusD = '1';
      if (status == '1') {
        msg = '发布';
      } else if (status == '0') {
        msg = '撤回';
      } else if (status == '3') {
        msg = '删除';
        statusD = '0';
        publishStatus = '';
      }
      this.$confirm('确定' + msg + '当前方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let data = {
            uuid: planId,
            publishStatus: publishStatus,
            status: statusD,
          };
          updateGoodsActivityStatus(data).then((res) => {
            if (res.code == '1') {
              this.$message({
                showClose: true,
                message: msg + '成功',
                type: 'success',
              });
              this.promotionList();
            } else {
              this.$message.error(msg + '失败');
            }
            this.loading = false;
          });
        })
        .catch(() => {});
    },
    //数字格式化
    dateRange(row, column, cellValue, index) {
      if (row.beginTime != null && row.beginTime.toString().length >= 10) {
        return (
          row.beginTime.toString().substr(0, 10) +
          ' — ' +
          row.endTime.toString().substr(0, 10)
        );
      } else {
        return '—';
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    to.meta.keepAlive = false; // C 跳转到 A 时让 A 不缓存，即刷新
    next();
  },
};
</script>
<style lang="less" scoped>
.toptitle {
  border: 1px solid #e0e0e0;
  border-bottom: 2px solid #188097;
  background: #f5f5f5;
  line-height: 35px;
  margin-bottom: 10px;
  padding: 0 10px;
  font-size: 14px;
  font-weight: bold;
}
.el-input--small .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.demo-form-inline {
  //   border: 1px solid #ebeef5;
  padding: 20px 10px 0px 30px;
}
.el-dialog-star {
  min-width: 800px;
}
.el-dialog-star .el-dialog__header {
  background: #f5f7fa;
  padding: 15px 20px;
}
.el-dialog-star .el-dialog__body {
  padding: 10px 20px 20px;
}
</style>
